class TodoManager {
    constructor() {
        this.tasks = this.loadTasks();
        this.currentFilter = 'all';
        this.init();
    }

    init() {
        this.bindEvents();
        this.render();
    }

    bindEvents() {
        const addBtn = document.getElementById('addTaskBtn');
        const titleInput = document.getElementById('taskTitle');
        const descInput = document.getElementById('taskDescription');
        const filters = document.querySelectorAll('input[name="filter"]');

        addBtn.addEventListener('click', () => this.addTask());
        titleInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addTask();
        });

        filters.forEach(filter => {
            filter.addEventListener('change', (e) => {
                this.currentFilter = e.target.value;
                this.render();
            });
        });
    }

    loadTasks() {
        const saved = localStorage.getItem('todoTasks');
        return saved ? JSON.parse(saved) : [];
    }

    saveTasks() {
        localStorage.setItem('todoTasks', JSON.stringify(this.tasks));
    }

    addTask() {
        const titleInput = document.getElementById('taskTitle');
        const descInput = document.getElementById('taskDescription');
        
        const title = titleInput.value.trim();
        if (!title) {
            alert('请输入任务标题！');
            return;
        }

        const task = {
            id: Date.now(),
            title: title,
            description: descInput.value.trim(),
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.tasks.unshift(task);
        this.saveTasks();
        
        titleInput.value = '';
        descInput.value = '';
        
        this.render();
    }

    toggleTask(id) {
        const task = this.tasks.find(t => t.id === id);
        if (task) {
            task.completed = !task.completed;
            this.saveTasks();
            this.render();
        }
    }

    deleteTask(id) {
        if (confirm('确定要删除这个任务吗？')) {
            this.tasks = this.tasks.filter(t => t.id !== id);
            this.saveTasks();
            this.render();
        }
    }

    getFilteredTasks() {
        switch (this.currentFilter) {
            case 'pending':
                return this.tasks.filter(t => !t.completed);
            case 'completed':
                return this.tasks.filter(t => t.completed);
            default:
                return this.tasks;
        }
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) return '刚刚';
        if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
        if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
        if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`;
        
        return date.toLocaleDateString('zh-CN');
    }

    render() {
        const taskList = document.getElementById('taskList');
        const filteredTasks = this.getFilteredTasks();
        
        this.updateStats();
        
        if (filteredTasks.length === 0) {
            taskList.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-clipboard-list"></i>
                    <p>${this.currentFilter === 'all' ? '暂无待办事项' : 
                        this.currentFilter === 'pending' ? '暂无未完成任务' : '暂无已完成任务'}</p>
                    <small>${this.currentFilter === 'all' ? '添加一个任务开始吧！' : ''}</small>
                </div>
            `;
            return;
        }

        taskList.innerHTML = filteredTasks.map(task => `
            <div class="task-item ${task.completed ? 'completed' : ''}" data-id="${task.id}">
                <input type="checkbox" class="task-checkbox" 
                       ${task.completed ? 'checked' : ''} 
                       onchange="todoManager.toggleTask(${task.id})">
                <div class="task-content">
                    <div class="task-title">${this.escapeHtml(task.title)}</div>
                    ${task.description ? `<div class="task-description">${this.escapeHtml(task.description)}</div>` : ''}
                    <div class="task-meta">创建于 ${this.formatDate(task.createdAt)}</div>
                </div>
                <div class="task-actions">
                    <button class="delete-btn" onclick="todoManager.deleteTask(${task.id})" title="删除任务">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `).join('');
    }

    updateStats() {
        const total = this.tasks.length;
        const completed = this.tasks.filter(t => t.completed).length;
        const pending = total - completed;

        document.getElementById('totalTasks').textContent = total;
        document.getElementById('pendingTasks').textContent = pending;
        document.getElementById('completedTasks').textContent = completed;
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 初始化应用
const todoManager = new TodoManager();

// 添加一些演示数据（仅在首次使用时）
if (localStorage.getItem('todoTasks') === null) {
    const demoTasks = [
        {
            id: 1,
            title: '欢迎使用待办事项管理',
            description: '这是一个简洁高效的待办事项管理工具',
            completed: false,
            createdAt: new Date(Date.now() - 3600000).toISOString()
        },
        {
            id: 2,
            title: '完成任务示例',
            description: '勾选左侧复选框来标记任务为已完成',
            completed: true,
            createdAt: new Date(Date.now() - 7200000).toISOString()
        }
    ];
    
    todoManager.tasks = demoTasks;
    todoManager.saveTasks();
    todoManager.render();
}
